<?php

namespace app\admin\controller;

use support\Request;
use app\common\Attribute;
use app\common\View;
use Webman\Captcha\CaptchaBuilder;
use app\model\Admin;
use app\model\AdminRole;


#[Attribute(title: "登记")]
class LoginController
{
    #[Attribute(isAuth: false, isPage: false, title: "登录")]
    public function log(Request $request)
    {
        if ($request->method() == "POST") {
            $all = $request->all();
            if (strtolower($all["captcha"]) !== $request->session()->get('captcha')) {
                return error(msg: "验证码不正确", data: ["key" => 'captcha', "msg" => "请输入正确的验证码"]);
            }
            $find = Admin::withJoin(['role' => ['role.name' => 'role']], 'left')->where("username", $all["username"])->find();
            if ($find) {
                if ($find["blacklist"] == "hidden") {
                    return error("账户不可用");
                }
                if (password_verify($all["password"], $find["password"])) {
                    $auth = ["role" => "超级管理员", "rid" => 0];
                    if ($find["rid"] != 0) {
                        $adminRole = AdminRole::where("id", $find["rid"])->value("auth");
                        $auth = ["role" => $find["role"], "auth" => $adminRole, "rid" => $find["rid"]];
                    }
                    $find["role"] = $auth["role"];
                    session(['user' => $find, "auth" => $auth]);
                    return success("登录成功", route("admin.index.index"));
                } else {
                    return error(msg: "登录失败", data: ["key" => 'password', "msg" => "密码错误"]);
                }
            } else {
                return error(msg: "登录失败", data: ["key" => 'username', "msg" => "用户名不存在"]);
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: false, isPage: false, title: "验证码")]
    public function captcha(Request $request)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build(width: 120);
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    #[Attribute(isAuth: false, isPage: false, title: "退出登录")]
    public function logOut(Request $request)
    {
        $request->session()->flush();
        return success("成功退出登录", route("admin.login.log"));
    }
}
